package com.googlecode.ascrblr.api.data;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.logging.Logger;

import org.xml.sax.SAXException;

import com.googlecode.ascrblr.api.HttpRequest;
import com.googlecode.ascrblr.api.Service;
import com.googlecode.ascrblr.api.HttpRequest.RequestType;
import com.googlecode.ascrblr.api.util.ServiceException;

public class DataService extends Service {

	/** 
	 * Logger instance. 
	 */
	public static Logger logger = Logger.getLogger(DataService.class.getName());
	
	/** 
	 * Version string 
	 */
	private static final String version = "1.0";
	
	/**
	 * Singleton
	 */
	private static volatile DataService instance;
	
	/**
	 * Default constructor
	 */
	private DataService() {}
	
	/**
	 * Returns a <code>DataService</code> instance.
	 * 
	 * @return
	 */
	public static DataService getInstance() {
		
		if(instance == null) {
			synchronized(DataService.class) {
				if(instance == null) {
					instance = new DataService();
				}
			}
		}
		
		return instance;
		
	}
	
	/**
	 * Gets a feed from the Audioscrobbler Data API.
	 * 
	 * @param feedClass
	 *            Feed class
	 * @return Parsed feed
	 * @throws IOException
	 * @throws ServiceException
	 */
	public Feed getFeed(Feed feed) throws IOException, ServiceException {

		InputStream resultStream = null;

		try {

			HttpRequest request = requestFactory.getRequest(RequestType.QUERY,
					new URL(feed.getUrl()));

			if (connectTimeout > 0) {
				request.setConnectTimeout(connectTimeout);
			}

			if (readTimeout > 0) {
				request.setReadTimeout(readTimeout);
			}

			// Execute the request
			request.execute();
			resultStream = request.getResponseStream();

			feed.parse(resultStream);

			return feed;

		} catch (SAXException e) {

			throw new ServiceException(e);

		} finally {
			if (resultStream != null) {
				resultStream.close();
			}
		}

	}

	/*
	 * (non-Javadoc)
	 * @see com.googlecode.ascrblr.api.Service#getVersion()
	 */
	@Override
	public String getVersion() {
		
		return version;
		
	}

}
